package com.syni.mdd.sjb.common.datatreaure.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.syni.mdd.sjb.common.component.mybatis.dxshapp.entity.DxshAppNews;
import com.syni.mdd.sjb.common.component.mybatis.dxshapp.entity.DxshAppUserChannel;
import com.syni.mdd.sjb.common.component.mybatis.dxshapp.entity.customBo.DxshAppNewsBo;
import com.syni.mdd.sjb.common.component.mybatis.dxshapp.mapper.DxshAppNewsMapper;
import com.syni.mdd.sjb.common.component.utils.common.utils.*;
import com.syni.mdd.sjb.common.component.utils.feign.dto.mdd.sjb.common.dxshapp.CommonPushToDsxhAppDto;
import com.syni.mdd.sjb.common.component.utils.feign.dto.mddAll.apiAuroraPush.CommonPushDto;
import com.syni.mdd.sjb.common.component.utils.feign.service.mddAll.AuroraPushRestService;
import com.syni.mdd.sjb.common.component.utils.feign.service.mdd.commonuser.UserRestService;
import com.syni.mdd.sjb.common.datatreaure.service.*;
import com.syni.mdd.sjb.common.datatreaure.constants.Constants;
import com.syni.mdd.sjb.common.datatreaure.constants.ResultCode;
import com.syni.mdd.sjb.common.datatreaure.constants.ResultMsg;
import com.syni.mdd.sjb.common.datatreaure.entity.bo.apiNews.MinAppNewsBo;
import com.syni.mdd.sjb.common.datatreaure.entity.vo.rp.dxshAppNews.CommonPushToDsxhUserRpVo;
import com.syni.mdd.sjb.common.datatreaure.entity.vo.rp.dxshAppNews.GetBusinessPayDataRpVo;
import com.syni.mdd.sjb.common.datatreaure.entity.vo.rp.dxshAppNews.GetUnreadMessageRpVo;
import com.syni.mdd.sjb.common.datatreaure.entity.vo.rp.dxshAppNews.ReceivedNewsRpVo;
import com.syni.mdd.sjb.common.datatreaure.entity.vo.rq.BaseRqVo;
import com.syni.mdd.sjb.common.datatreaure.entity.vo.rq.apiAppNews.BankNewsRqVo;
import com.syni.mdd.sjb.common.datatreaure.entity.vo.rq.apiAppNews.CreateNewsRqVo;
import com.syni.mdd.sjb.common.datatreaure.entity.vo.rq.dxshAppNews.ReceivedNewsVo;
import com.syni.mdd.sjb.common.datatreaure.mybatis.MybatisUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 电享生活app消息表 服务实现类
 * </p>
 *
 * @author cfx
 * @since 2020-04-21
 */
@Service
@Log4j2
public class DxshAppNewsServiceImpl extends ServiceImpl<DxshAppNewsMapper, DxshAppNews> implements DxshAppNewsService {

    public final static Map<Integer,Integer> APP_NEW_TYPE = new HashMap<>();

    static {
        APP_NEW_TYPE.put(Constants.APP_NEWS_MINAPP, Constants.COMMON_FLAG_TRUE_INT);
        APP_NEW_TYPE.put(Constants.APP_NEWS_MIDONGDONG, Constants.COMMON_FLAG_TRUE_INT);
        APP_NEW_TYPE.put(Constants.APP_NEWS_MT_SMART, Constants.COMMON_FLAG_TRUE_INT);
        APP_NEW_TYPE.put(Constants.APP_NEWS_SYSTEM, Constants.COMMON_FLAG_TRUE_INT);
    }

    public static final String BUSINESS_DXSH_PREFIX = "B_DXSH_";
    //public static final String BUSINESS_DXSH_PREFIX = "B";

    @Autowired
    DxshAppNewsMapper dxshAppNewsMapper;

    @Autowired
    AuroraPushRestService auroraPushRestService;

    @Autowired
    UserRestService userRestService;

    @Autowired
    DxshAppUserNewsSwitchService dxshAppUserNewsSwitchService;

    @Autowired
    DxshAppUserChannelService dxshAppUserChannelService;

    @Autowired
    DxshAppNewsPushService dxshAppNewsPushService;

    @Autowired
    DankMerchantsDefBusinessService dankMerchantsDefBusinessService;


    @Override
    public Map<String, Object> receivedNews(ReceivedNewsVo receivedNewsVo) {
        Page page = new Page(receivedNewsVo.getPageNum(),receivedNewsVo.getPageSize());
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(DxshAppNews.USER_ID,receivedNewsVo.getUserId());
        queryWrapper.eq(DxshAppNews.ROLE_ID,Constants.DXSH_ROLE_ID);
        queryWrapper.eq(DxshAppNews.IS_CLEAR,Constants.COMMON_FLAG_FALSE_INT);
        queryWrapper.orderByDesc(DxshAppNews.UPDATE_TIME);
        if(APP_NEW_TYPE.containsKey(receivedNewsVo.getRange())){
            queryWrapper.eq(DxshAppNews.TYPE,receivedNewsVo.getRange());
        }
        IPage<DxshAppNews> dxshAppNewsIPage = dxshAppNewsMapper.selectPage(page,queryWrapper);
        Map<String,Object> userData = MybatisUtils.UserData(dxshAppNewsIPage);
        List<ReceivedNewsRpVo> receivedNewsRpVos = new ArrayList<>();
        List<DxshAppNews> dxshAppNews = dxshAppNewsIPage.getRecords();
        dxshAppNews.forEach(dxnews -> {
            ReceivedNewsRpVo receivedNewsRpVo = new ReceivedNewsRpVo();
            receivedNewsRpVo.setId(dxnews.getId());
            receivedNewsRpVo.setParentType(dxnews.getType());
            receivedNewsRpVo.setType(dxnews.getType());
            receivedNewsRpVo.setUpdateTime(dxnews.getUpdateTime());
            receivedNewsRpVo.setTitle(dxnews.getTitle());
            receivedNewsRpVo.setIcon(dxnews.getIcon());
            receivedNewsRpVo.setDescribes(dxnews.getDescribes());
            receivedNewsRpVo.setDetailParams(JSON.parseObject(dxnews.getContent()));
            receivedNewsRpVos.add(receivedNewsRpVo);
        });
        //修改读过的消息
        updteAlreadyNews(receivedNewsVo.getUserId());
        if(receivedNewsVo.getDxshMessageId() != null){
            DxshAppNews highLightNew = dxshAppNewsMapper.selectById(receivedNewsVo.getDxshMessageId());
            if(highLightNew != null){
                ReceivedNewsRpVo receivedNewsRpVo = new ReceivedNewsRpVo();
                receivedNewsRpVo.setId(highLightNew.getId());
                receivedNewsRpVo.setParentType(highLightNew.getType());
                receivedNewsRpVo.setType(highLightNew.getType());
                receivedNewsRpVo.setUpdateTime(highLightNew.getUpdateTime());
                receivedNewsRpVo.setTitle(highLightNew.getTitle());
                receivedNewsRpVo.setIcon(highLightNew.getIcon());
                receivedNewsRpVo.setDescribes(highLightNew.getDescribes());
                receivedNewsRpVo.setDetailParams(JSON.parseObject(highLightNew.getContent()));
                receivedNewsRpVos.add(0,receivedNewsRpVo);
            }
        }
        return ResultMapHelper.success(receivedNewsRpVos,userData, ResultMsg.MSG_GET_SUCCESS);
    }

    /**
     * @Description 点击详情，将消息设置成已读
     * @Param userId
     * @Author: cfx
     * @Date: 2020/5/6
     */
    private void updteAlreadyNews(Integer userId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(DxshAppNews.USER_ID,userId);
        queryWrapper.eq(DxshAppNews.IS_WATCH,Constants.COMMON_FLAG_FALSE_INT);
        LocalDateTime nowTime = DateTimeUtils.converDateToLocalDateTime(new Date());
        queryWrapper.lt(DxshAppNews.NEW_TIME,nowTime);
        List<DxshAppNews> dxshAppNews = dxshAppNewsMapper.selectList(queryWrapper);
        if(CollectionUtils.isNotEmpty(dxshAppNews)){
            dxshAppNews.forEach(dn -> {
                dn.setIsWatch(Constants.COMMON_FLAG_TRUE_INT);
            });
            this.updateBatchById(dxshAppNews);
        }
    }

    public Map<String, Object> pushNewsToApp(DxshAppNews dxshAppNews) {
        CommonPushDto commonPushDto = new CommonPushDto();
        List<String> alias = new ArrayList<>();
        alias.add(BUSINESS_DXSH_PREFIX + dxshAppNews.getUserId());
        commonPushDto.setAlias(JSON.toJSONString(alias));
        commonPushDto.setRoleId(Constants.DXSH_ROLE_ID);
        commonPushDto.setCode(dxshAppNews.getCode());
        commonPushDto.setAlert(dxshAppNews.getTitle());
        auroraPushRestService.commonPush(commonPushDto);
        //更新到数据库
        CommonPushToDsxhUserRpVo commonPushToDsxhUserRpVo = new CommonPushToDsxhUserRpVo();
        commonPushToDsxhUserRpVo.setNewId(dxshAppNews.getId());
        return ResultMapHelper.success(commonPushToDsxhUserRpVo,ResultMsg.HAND_SUCCESS);
    }

    @Override
    @Transactional
    public RpcResponseVo commonPushToDsxhApp(CommonPushToDsxhAppDto commonPushToDsxhAppDto) {
        //
        if(commonPushToDsxhAppDto.getType() == Constants.APP_NEWS_MINAPP){
            RpcResponseVo rpcResponseVo = userRestService.getUserIdByMiniToken(commonPushToDsxhAppDto.getToken());
            if(rpcResponseVo.isSuccess()){
                Map<String,Object> data = (Map<String, Object>) rpcResponseVo.getData();
                if(data.containsKey("userId") && StringUtils.checkNullAndEmpty(data.get("userId"))){
                    String userId = data.get("userId").toString();
                    commonPushToDsxhAppDto.setUserId(Integer.parseInt(userId));
                }
            }else {
                return RpcResponseVo.result(ResultCode.CODE_ERROR_100,"用户不存在");
            }
        }else if(commonPushToDsxhAppDto.getType() == Constants.APP_NEWS_MIDONGDONG){

        }
        //commonPushToDsxhAppDto.setUserId(462); //写死
        Set<Integer> types = dxshAppUserNewsSwitchService.getNewsSwitchByUserId(commonPushToDsxhAppDto.getUserId());
        if(!types.contains(commonPushToDsxhAppDto.getType())){
            return RpcResponseVo.success(null,ResultMsg.HAND_SUCCESS);
        }
        //更新到数据库
        DxshAppNews dxshAppNews = updateDxshAppNes(commonPushToDsxhAppDto);
        CommonPushDto commonPushDto = new CommonPushDto();
        BeanUtils.copyProperties(commonPushToDsxhAppDto,commonPushDto);
        List<String> alias = new ArrayList<>();
        alias.add(BUSINESS_DXSH_PREFIX + commonPushToDsxhAppDto.getUserId());
        commonPushDto.setAlias(JSON.toJSONString(alias));
        commonPushDto.setRoleId(Constants.DXSH_ROLE_ID);
        commonPushDto.setCode(Constants.UNIFIED_MESSAGE_PUSH);
        //重新设置推送值和推送码
        Map<String,Object> messageData = new HashMap<>();
        messageData.put("type",dxshAppNews.getType());
        messageData.put("dxshMessageId",dxshAppNews.getId());
        commonPushDto.setContent(JSON.toJSONString(messageData));
        auroraPushRestService.commonPush(commonPushDto);
        CommonPushToDsxhUserRpVo commonPushToDsxhUserRpVo = new CommonPushToDsxhUserRpVo();
        commonPushToDsxhUserRpVo.setNewId(dxshAppNews.getId());
        return RpcResponseVo.success(commonPushToDsxhUserRpVo,ResultMsg.HAND_SUCCESS);
    }

    @Override
    public RpcResponseVo commonPushToDsxhApp_v2(CommonPushToDsxhAppDto commonPushToDsxhAppDto) {
        log.info("commonPushToDsxhAppDto:" + JSON.toJSONString(commonPushToDsxhAppDto));
        if(commonPushToDsxhAppDto.getType() == Constants.APP_NEWS_MINAPP){
            RpcResponseVo rpcResponseVo = userRestService.getUserInfoByPhone(commonPushToDsxhAppDto.getPhone());
            if(rpcResponseVo.isSuccess()){
                Map<String,Object> data = (Map<String, Object>) rpcResponseVo.getData();
                if(data.containsKey("userId") && StringUtils.checkNullAndEmpty(data.get("userId"))){
                    String userId = data.get("userId").toString();
//                    Integer businessId = dankMerchantsDefBusinessService.getChooseBusinessId(Integer.parseInt(userId));
//                    if(businessId == null){
//                        return RpcResponseVo.result(ResultCode.CODE_ERROR,ResultMsg.CODE_ERROR_110);
//                    }
                    commonPushToDsxhAppDto.setUserId(Integer.parseInt(userId));
//                    commonPushToDsxhAppDto.setBusinessId(businessId);
                    JSONObject minAppData = JSON.parseObject(commonPushToDsxhAppDto.getContent());
                    Integer appStatus = minAppData.getInteger("appStatus");
                    Integer wxReleaseStep = minAppData.getInteger("wxReleaseStep");
                    String wxReleaseStatus = minAppData.getString("wxReleaseStatus");
                    Integer type = minAppData.getInteger("type");
                    MinAppNewsBo minAppNewsBo = new MinAppNewsBo();
                    minAppNewsBo.setAppStatus(appStatus);
                    minAppNewsBo.setWxReleaseStep(wxReleaseStep);
                    minAppNewsBo.setWxReleaseStatus(wxReleaseStatus);
                    if(type != null && type == Constants.JUMP_TARGET){
                        minAppNewsBo.setNewAction(Constants.JUMP_TARGET);
                        minAppNewsBo.setJumpTo(minAppData.getString("jumpTo"));
                        minAppNewsBo.setIsFill(Constants.COMMON_FLAG_TRUE_INT);
                        minAppNewsBo.setAppStatus(Constants.MINAPP_STATUS_CREATE_SUCCESS);
                    }
                    if(minAppData.containsKey("storeId") && StringUtils.isNotBlank(minAppData.getString("storeId"))){
                        commonPushToDsxhAppDto.setStoreId(minAppData.getString("storeId"));
                    }
                    if(commonPushToDsxhAppDto.getStoreId() != null && minAppNewsBo.getAppStatus() != null) {
                        commonPushToDsxhAppDto.setStoreId(commonPushToDsxhAppDto.getStoreId());
                        dxshAppUserChannelService.postHandleMinAppNews(minAppNewsBo, commonPushToDsxhAppDto.getStoreId());//查询小程序记录
                        DxshAppUserChannel dxshAppUserChannel = dxshAppUserChannelService.getByMinAppId(commonPushToDsxhAppDto.getStoreId());
                        if(dxshAppUserChannel != null){
                            minAppNewsBo.setMinAppId(dxshAppUserChannel.getMinAppId());
                        }
                    }
                    if(minAppData.containsKey("messageType")){
                        commonPushToDsxhAppDto.setMessageType(minAppData.getInteger("messageType"));
                        if(commonPushToDsxhAppDto.getMessageType() == Constants.DXSH_APP_NEW_ORTHER){
                            commonPushToDsxhAppDto.setMainTitle("小程序消息");
                        }
                    }
                    if(minAppData.containsKey("mainTitle")){
                        commonPushToDsxhAppDto.setMainTitle(minAppData.getString("mainTitle"));
                    }

                    commonPushToDsxhAppDto.setContent(JSON.toJSONString(minAppNewsBo));
                }
            }else {
                return RpcResponseVo.result(ResultCode.CODE_ERROR_100,"用户不存在");
            }
        }else if(commonPushToDsxhAppDto.getType() == Constants.APP_NEWS_MIDONGDONG){

        }else if(commonPushToDsxhAppDto.getType() == Constants.APP_NEWS_MT_SMART){

        }
        if(StringUtils.isNotBlank(commonPushToDsxhAppDto.getCode())){
            commonPushToDsxhAppDto.setCode(commonPushToDsxhAppDto.getCode());
        }else {
            commonPushToDsxhAppDto.setCode(Constants.UNIFIED_MESSAGE_PUSH);
        }
        DxshAppNews dxshAppNews = updateDxshAppNes(commonPushToDsxhAppDto);
        CommonPushDto commonPushDto = new CommonPushDto();
        commonPushDto.setCode(commonPushToDsxhAppDto.getCode());
        BeanUtils.copyProperties(commonPushToDsxhAppDto,commonPushDto);
        List<String> alias = new ArrayList<>();
        alias.add(BUSINESS_DXSH_PREFIX + commonPushToDsxhAppDto.getUserId());
        commonPushDto.setAlias(JSON.toJSONString(alias));
        commonPushDto.setRoleId(Constants.DXSH_ROLE_ID);
        //重新设置推送值和推送码
        Map<String,String> messageData = new HashMap<>();
        messageData.put("type",dxshAppNews.getType().toString());
        messageData.put("dxshMessageId",dxshAppNews.getId().toString());
        commonPushDto.setContent(JSON.toJSONString(messageData));
        Set<Integer> types = dxshAppUserNewsSwitchService.getNewsSwitchByUserId_v2(commonPushToDsxhAppDto.getUserId(),
                commonPushToDsxhAppDto.getMessageType(),commonPushToDsxhAppDto.getMessageSecondType());

        if(types.contains(commonPushToDsxhAppDto.getMessageSecondType()) && dxshAppNewsPushService.checkHavePush(commonPushToDsxhAppDto.getUserId())){
            //判断时段
            auroraPushRestService.commonPush(commonPushDto);
        }
        CommonPushToDsxhUserRpVo commonPushToDsxhUserRpVo = new CommonPushToDsxhUserRpVo();
        commonPushToDsxhUserRpVo.setNewId(dxshAppNews.getId());
        return RpcResponseVo.success(commonPushToDsxhUserRpVo,ResultMsg.HAND_SUCCESS);
    }

    public void commonPushToDsxhAppHandler(CommonPushToDsxhAppDto commonPushToDsxhAppDto) {
        log.info("commonPushToDsxhAppHandler:" + JSON.toJSONString(commonPushToDsxhAppDto));
        if(commonPushToDsxhAppDto.getType() == Constants.APP_NEWS_MINAPP){

        }else if(commonPushToDsxhAppDto.getType() == Constants.APP_NEWS_MIDONGDONG){

        }else if(commonPushToDsxhAppDto.getType() == Constants.APP_NEWS_MT_SMART){

        }
        if(StringUtils.isNotBlank(commonPushToDsxhAppDto.getCode())){
            commonPushToDsxhAppDto.setCode(commonPushToDsxhAppDto.getCode());
        }else {
            commonPushToDsxhAppDto.setCode(Constants.UNIFIED_MESSAGE_PUSH);
        }
        DxshAppNews dxshAppNews = updateDxshAppNes(commonPushToDsxhAppDto);
        CommonPushDto commonPushDto = new CommonPushDto();
        commonPushDto.setCode(commonPushToDsxhAppDto.getCode());
        BeanUtils.copyProperties(commonPushToDsxhAppDto,commonPushDto);
        List<String> alias = new ArrayList<>();
        alias.add(BUSINESS_DXSH_PREFIX + commonPushToDsxhAppDto.getUserId());
        commonPushDto.setAlias(JSON.toJSONString(alias));
        commonPushDto.setRoleId(Constants.DXSH_ROLE_ID);
        //重新设置推送值和推送码
        Map<String,String> messageData = new HashMap<>();
        messageData.put("type",dxshAppNews.getType().toString());
        messageData.put("dxshMessageId",dxshAppNews.getId().toString());
        commonPushDto.setContent(JSON.toJSONString(messageData));
        Set<Integer> types = dxshAppUserNewsSwitchService.getNewsSwitchByUserId_v2(commonPushToDsxhAppDto.getUserId(),
                commonPushToDsxhAppDto.getMessageType(),commonPushToDsxhAppDto.getMessageSecondType());
        if(types.contains(commonPushToDsxhAppDto.getMessageSecondType()) && dxshAppNewsPushService.checkHavePush(commonPushToDsxhAppDto.getUserId())) {
            //判断时段
            auroraPushRestService.commonPush(commonPushDto);
        }
    }

    private DxshAppNews updateDxshAppNes(CommonPushToDsxhAppDto commonPushToDsxhAppDto) {
        DxshAppNews dxshAppNews = new DxshAppNews();
        dxshAppNews.setTitle(commonPushToDsxhAppDto.getAlert());
        dxshAppNews.setUserId(commonPushToDsxhAppDto.getUserId());
        dxshAppNews.setRoleId(Constants.DXSH_ROLE_ID);
        dxshAppNews.setCode(commonPushToDsxhAppDto.getCode());
        dxshAppNews.setType(commonPushToDsxhAppDto.getType());
        dxshAppNews.setContent(commonPushToDsxhAppDto.getContent());
        dxshAppNews.setUpdateTime(LocalDateTime.now());
        dxshAppNews.setNewTime(LocalDateTime.now());
        dxshAppNews.setDescribes(commonPushToDsxhAppDto.getDescribes());
        dxshAppNews.setMainTitle(commonPushToDsxhAppDto.getMainTitle());
        dxshAppNews.setMessageType(commonPushToDsxhAppDto.getMessageType());
        dxshAppNews.setMessageSecondType(commonPushToDsxhAppDto.getMessageSecondType());
        dxshAppNews.setBusinessId(commonPushToDsxhAppDto.getBusinessId());
        dxshAppNews.setStoreId(commonPushToDsxhAppDto.getStoreId());
        dxshAppNewsMapper.insert(dxshAppNews);
        return dxshAppNews;
    }

    @Override
    public Map<String, Object> getUnreadMessage(BaseRqVo baseRqVo) {
        Integer userId = baseRqVo.getUserId();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(DxshAppNews.USER_ID,userId);
        queryWrapper.eq(DxshAppNews.IS_WATCH,Constants.COMMON_FLAG_FALSE_INT);
        Integer count = this.count(queryWrapper);
        GetUnreadMessageRpVo getUnreadMessageRpVo = new GetUnreadMessageRpVo();
        getUnreadMessageRpVo.setNotReadCount(count);
        //获取最新的一条通知
        queryWrapper.orderByDesc(DxshAppNews.NEW_TIME);
        Page page = new Page(1,1);
        List<DxshAppNews> dxshAppNews = dxshAppNewsMapper.selectPage(page,queryWrapper).getRecords();
        if(CollectionUtils.isNotEmpty(dxshAppNews)){
            DxshAppNews daNew = dxshAppNews.get(0);
            getUnreadMessageRpVo.setTitle(daNew.getTitle());
            getUnreadMessageRpVo.setUpdateTime(daNew.getUpdateTime());
        }
        return ResultMapHelper.success(getUnreadMessageRpVo,ResultMsg.MSG_GET_SUCCESS);
    }

    @Override
    public Map<String, Object> clearNews(BaseRqVo baseRqVo) {
        Integer userId = baseRqVo.getUserId();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(DxshAppNews.USER_ID,userId);
        queryWrapper.eq(DxshAppNews.IS_CLEAR,Constants.COMMON_FLAG_FALSE_INT);
        List<DxshAppNews> dxshAppNews = dxshAppNewsMapper.selectList(queryWrapper);
        if(CollectionUtils.isNotEmpty(dxshAppNews)){
            dxshAppNews.forEach(dn -> {
                dn.setIsClear(Constants.COMMON_FLAG_TRUE_INT);
            });
            this.saveOrUpdateBatch(dxshAppNews);
        }
        return ResultMapHelper.success(null,ResultMsg.HAND_SUCCESS);
    }

    @Override
    public Map<String, Object> test(BaseRqVo baseRqVo) {
        DxshAppNews dxshAppNews = dxshAppNewsMapper.selectById(13);
        return this.pushNewsToApp(dxshAppNews);
    }

    @Override
    public List<DxshAppNewsBo> countByMessageType(QueryWrapper queryWrapper) {
        return dxshAppNewsMapper.countNoReadByMessageType(queryWrapper);
    }

    @Override
    public Integer getUserNoReadMddMessageCount(Integer userId,Integer businessId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(DxshAppNews.USER_ID,userId);
        queryWrapper.eq(DxshAppNews.IS_CLEAR,Constants.COMMON_FLAG_FALSE_INT);
        queryWrapper.eq(DxshAppNews.IS_WATCH,Constants.COMMON_FLAG_FALSE_INT);
        queryWrapper.eq(DxshAppNews.BUSINESS_ID,businessId);
        queryWrapper.eq(DxshAppNews.TYPE,Constants.APP_NEWS_MIDONGDONG);
        return dxshAppNewsMapper.selectCount(queryWrapper);
    }

    @Override
    public Integer getUserNoReadMinAppMessageCount(Integer userId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(DxshAppNews.USER_ID,userId);
        queryWrapper.eq(DxshAppNews.IS_CLEAR,Constants.COMMON_FLAG_FALSE_INT);
        queryWrapper.eq(DxshAppNews.IS_WATCH,Constants.COMMON_FLAG_FALSE_INT);
        queryWrapper.eq(DxshAppNews.TYPE,Constants.APP_NEWS_MINAPP);
        return dxshAppNewsMapper.selectCount(queryWrapper);
    }



    @Override
    public Map<String, Object> getBusinessPayData(BankNewsRqVo bankNewsRqVo) {
        GetBusinessPayDataRpVo getBusinessPayData = new GetBusinessPayDataRpVo();
        Integer newId = bankNewsRqVo.getNewId();
        DxshAppNews dxshAppNews = dxshAppNewsMapper.selectById(newId);
        if(dxshAppNews == null){
            return ResultMapHelper.result(ResultCode.CODE_ERROR_100,ResultMsg.CODE_ERROR_05);
        }
        Map<String,Object> content = JSON.parseObject(dxshAppNews.getContent());
        String detailContent = content.get("content").toString();
        Map<String,Object> detailContentMap = JSON.parseObject(detailContent);
        if(detailContentMap.containsKey("alipayUser")){
            getBusinessPayData.setAlipayUser(detailContentMap.get("alipayUser").toString());
        }
        if(detailContentMap.containsKey("alipayType")){
            getBusinessPayData.setAlipayType(Integer.parseInt(detailContentMap.get("alipayType").toString()));
        }
        if(detailContentMap.containsKey("alipayUid")){
            getBusinessPayData.setAlipayUid(detailContentMap.get("alipayUid").toString());
        }
        if(detailContentMap.containsKey("alipayAccount")){
            getBusinessPayData.setAlipayAccount(detailContentMap.get("alipayAccount").toString());
        }
        return ResultMapHelper.success(getBusinessPayData,ResultMsg.MSG_GET_SUCCESS);
    }

    public Map<String, Object> confirmUidNews(BankNewsRqVo bankNewsRqVo) {
        Integer newId = bankNewsRqVo.getNewId();
        DxshAppNews dxshAppNews = dxshAppNewsMapper.selectById(newId);
        if(dxshAppNews == null){
            return ResultMapHelper.result(ResultCode.CODE_ERROR_100,ResultMsg.CODE_ERROR_05);
        }
        Map<String,Object> content = JSON.parseObject(dxshAppNews.getContent());
        String detailContent = content.get("content").toString();
        Map<String,Object> detailContentMap = JSON.parseObject(detailContent);
        Integer businessInfoId = Integer.parseInt(detailContentMap.get("businessInfoId").toString());
        Integer mddNewsId = Integer.parseInt(content.get("id").toString());
        Integer businessId = Integer.parseInt(content.get("bmsBusinessId").toString());
        Integer status = Constants.COMMON_FLAG_TRUE_INT;
        String postUrl = AppConfig.getProperty("mdd.dsp.api") + "/DSP_API/apiBusinessInfo/confirmUidNews";
        Map<String,Object> params = new LinkedHashMap<>();
        params.put("businessInfoId",businessInfoId);
        params.put("businessId",businessId);
        params.put("newId",mddNewsId);
        params.put("status",status);
        params.put("userIdentify",bankNewsRqVo.getUserId());
        String responseBody = RestTemplateUtils.postForEntityForJsonByLoadBalanced(postUrl,params);
        Map<String,Object> resultMap = JSON.parseObject(responseBody);
        if(ResultMapHelper.isSuccess(resultMap) || resultMap.get("status").equals("01")) {
            detailContentMap.put("status",Constants.COMMON_FLAG_TRUE_INT);
            content.put("content",JSON.toJSONString(detailContentMap));
            dxshAppNews.setContent(JSON.toJSONString(content));
            dxshAppNewsMapper.updateById(dxshAppNews);
            return ResultMapHelper.success(new HashMap<>(), ResultMsg.HAND_SUCCESS);
        }
        return ResultMapHelper.result(ResultCode.CODE_ERROR_100, resultMap.get("msg").toString());
    }

    @Override
    public Map<Integer,Integer> countByMddNoReadMessage(Set<Integer> businessIds) {
        Map<Integer,Integer> noReadNumMap = new HashMap<>();
        if(businessIds.size() > 0){
            Map<String,Object> queryMap = new HashMap<>();
            queryMap.put("businessIds",StringUtils.join(businessIds,","));
            List<DxshAppNewsBo> dxshAppNewsBos = dxshAppNewsMapper.countByMddNoReadMessage(queryMap);
            if(CollectionUtils.isNotEmpty(dxshAppNewsBos)){
                for(DxshAppNewsBo dxshAppNewsBo : dxshAppNewsBos){
                    noReadNumMap.put(dxshAppNewsBo.getBusinessId(),dxshAppNewsBo.getNum());
                }
            }
        }
        return noReadNumMap;
    }

    public Integer countByMddNoReadMessage(Integer businessId) {
        Set<Integer> businessIds = new HashSet<>();
        businessIds.add(businessId);
        if(businessIds.size() > 0){
            Map<String,Object> queryMap = new HashMap<>();
            queryMap.put("businessIds",StringUtils.join(businessIds,","));
            List<DxshAppNewsBo> dxshAppNewsBos = dxshAppNewsMapper.countByMddNoReadMessage(queryMap);
            if(CollectionUtils.isNotEmpty(dxshAppNewsBos)){
                return dxshAppNewsBos.get(0).getNum();
            }else {
                return 0;
            }
        }
        return 0;
    }

    @Override
    public DxshAppNews createNews(CreateNewsRqVo createNewsRqVo) {
        DxshAppNews dxshAppNews = new DxshAppNews();
        BeanUtils.copyProperties(createNewsRqVo,dxshAppNews);
        dxshAppNews.setNewTime(LocalDateTime.now());
        this.saveOrUpdate(dxshAppNews);
        return dxshAppNews;
    }

    @Override
    public Map<String, Integer> countByMinAppNoReadMessage(Set<String> storeIds) {
        Map<String,Integer> noReadNumMap = new HashMap<>();
        if(CollectionUtils.isNotEmpty(storeIds)) {
            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("storeIds", StringUtils.join(storeIds, ","));
            List<DxshAppNewsBo> dxshAppNewsBos = dxshAppNewsMapper.countByMinAppNoReadMessage(queryMap);
            if (CollectionUtils.isNotEmpty(dxshAppNewsBos)) {
                for (DxshAppNewsBo dxshAppNewsBo : dxshAppNewsBos) {
                    noReadNumMap.put(dxshAppNewsBo.getStoreId(), dxshAppNewsBo.getNum());
                }
            }
        }
        return noReadNumMap;
    }
}
